﻿using System;
using System.IO;
using System.Web.Mvc;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace MvcApplication1.Views.Utility
{
    public class PngResult : ContentResult
    {
        private readonly Action<DrawingContext> _drawingFunction;
        private readonly int _pixelWidth;
        private readonly int _pixelHeight;

        public PngResult(Action<DrawingContext> drawingFunction, int pixelWidth, int pixelHeight)
        {
            _drawingFunction = drawingFunction;
            _pixelWidth = pixelWidth;
            _pixelHeight = pixelHeight;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var encoder = new PngBitmapEncoder();
            var renderTargetBitmap = new RenderTargetBitmap(_pixelWidth, _pixelHeight, 96, 96, PixelFormats.Pbgra32);

            var drawingVisual = CharacterModel.Utility.GetScaledDrawingVisual(_drawingFunction, _pixelWidth, _pixelHeight, 10);

            renderTargetBitmap.Render(drawingVisual);

            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

            context.HttpContext.Response.ContentType = "image/png";

            var memoryStream = new MemoryStream();
            encoder.Save(memoryStream);

            memoryStream.Position = 0;
            context.HttpContext.Response.BinaryWrite(memoryStream.GetBuffer());
        }
    }
}